# -*- coding: utf-8 -*-

from odoo import models, fields, api


class MenuPermission(models.Model):
    """菜单权限"""
    _name = 'device.menu.permission'
    _description = '菜单权限'
    _order = 'sequence, name'
    _parent_name = "parent_id"
    _parent_store = True
    
    name = fields.Char('菜单名称', required=True)
    path = fields.Char('路由路径', required=True)
    component = fields.Char('组件路径')
    redirect = fields.Char('重定向')
    
    # 父子关系
    parent_id = fields.Many2one('device.menu.permission', '父菜单', ondelete='cascade')
    parent_path = fields.Char(index=True)
    child_ids = fields.One2many('device.menu.permission', 'parent_id', '子菜单')
    
    # 元数据
    meta_title = fields.Char('菜单标题')
    meta_icon = fields.Char('图标')
    meta_no_cache = fields.Boolean('不缓存', default=False)
    meta_breadcrumb = fields.Boolean('面包屑', default=True)
    meta_affix = fields.Boolean('固定标签', default=False)
    
    # 权限控制
    hidden = fields.Boolean('隐藏菜单', default=False)
    always_show = fields.Boolean('总是显示', default=False)
    
    sequence = fields.Integer('排序', default=10)
    active = fields.Boolean('启用', default=True)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Many2one('res.users', '创建者', default=lambda self: self.env.user)
    update_by = fields.Many2one('res.users', '更新者', default=lambda self: self.env.user)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        vals['update_by'] = self.env.user.id
        return super().write(vals)
    
    def get_menu_tree(self, user_menu_ids=None):
        """构建菜单树结构"""
        if user_menu_ids is None:
            menus = self.search([('active', '=', True)], order='sequence, name')
        else:
            menus = self.browse(user_menu_ids).filtered('active')
        
        menu_dict = {}
        for menu in menus:
            menu_dict[menu.id] = {
                'id': menu.id,
                'name': menu.name,
                'path': menu.path,
                'component': menu.component,
                'redirect': menu.redirect,
                'parent_id': menu.parent_id.id if menu.parent_id else None,
                'meta': {
                    'title': menu.meta_title,
                    'icon': menu.meta_icon,
                    'noCache': menu.meta_no_cache,
                    'breadcrumb': menu.meta_breadcrumb,
                    'affix': menu.meta_affix,
                },
                'hidden': menu.hidden,
                'alwaysShow': menu.always_show,
                'children': []
            }
        
        # 构建树结构
        root_menus = []
        for menu_id, menu_data in menu_dict.items():
            if menu_data['parent_id']:
                parent_menu = menu_dict.get(menu_data['parent_id'])
                if parent_menu:
                    parent_menu['children'].append(menu_data)
            else:
                root_menus.append(menu_data)
        
        return root_menus
